package com.gitee.yannzh.rune.core.base.vo;

import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * @author: yann
 * @description:  接口返回数据格式
 *
 * @date: 2023-12-20 16:03
 */
@Data
public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final String TRACE_ID = "traceId";

	/**
	 * 成功标志
	 */
//	@ApiModelProperty(value = "成功标志")
	private boolean success;

	/**
	 * 返回处理消息
	 */
	private String message = "操作成功！";

	/**
	 * 返回代码
	 */
	private int code = 0;

	/**
	 * 返回数据对象 data
	 */
	private T data;

	/**
	 * 时间戳
	 */
	private long timestamp = System.currentTimeMillis();

	private String requestId = MDC.get(TRACE_ID);

	public Result() {

	}


	public Result<T> success(String message) {
		this.message = message;
		this.code = 200;
		this.success = true;
		return this;
	}

	public static<T> Result<T> ok() {
		Result<T> result = new Result<T>();
		result.setSuccess(true);
		result.setCode(200);
		result.setMessage("成功");
		return result;
	}

	public static<T> Result<T> ok(T data) {
		Result<T> result = new Result<T>();
		result.setSuccess(true);
		result.setCode(200);
		result.setData(data);
		return result;
	}

	public static<T> Result<T> ok(String msg, T data) {
		Result<T> result = new Result<T>();
		result.setSuccess(true);
		result.setCode(200);
		result.setMessage(msg);
		result.setData(data);
		return result;
	}


	public static<T> Result<T> fail(String msg, T data) {
		Result<T> result = new Result<T>();
		result.setSuccess(false);
		result.setCode(500);
		result.setMessage(msg);
		result.setData(data);
		return result;
	}

	public static Result<Void> fail(String msg) {
		return fail(500, msg);
	}

	public static Result<Void> fail(int code, String msg) {
		Result<Void> result = new Result<>();
		result.setCode(code);
		result.setMessage(msg);
		result.setSuccess(false);
		return result;
	}

	public static<T> Result<T> error(String message) {
		Result<T> result = new Result<>();
		result.setSuccess(false);
		result.setCode(500);
		result.setMessage(message);
		return result;
	}

	public static<T> Result<T> error(int code, String message) {
		Result<T> result = new Result<>();
		result.setSuccess(false);
		result.setCode(code);
		result.setMessage(message);
		return result;
	}


	/**
	 * 无权限访问返回结果
	 */
	public static Result<Void> unauthorized(String msg) {
		return fail(401, msg);
	}


}
